package cn.lpq.magnetsearch.impl;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.json.JSONUtil;
import cn.lpq.magnetsearch.AbstractMagentSearch;
import cn.lpq.pojo.MagentInfo;

/**
 * http://torrentba.info 这个网站的磁力搜索
 * 
 * @author Administrator
 *
 */
public class TorrentbaMagentSearch extends AbstractMagentSearch {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private String queryUrl = "http://torrentba.info/s.php?q=";

	private List<MagentInfo> magentInfolist = new ArrayList<MagentInfo>();

	@Override
	public List<MagentInfo> magentSearch(String keyword) {
		magentInfolist.clear();
		try {
			keyword = URLEncoder.encode(keyword, "UTF-8");
			Connection.Response execute = Jsoup.connect(queryUrl + keyword).ignoreContentType(true).execute();
			// 获取返回数据
			String body = execute.body();
			Document doc = Jsoup.parse(body);
			Elements links = doc.select("div.torrentba_list li");
			for (Element link : links) {
				String fileName = link.select("a").text();
				String magent = "magnet:?xt=urn:btih:"
						+ link.select("a").attr("href").replace("http://torrentba.info/list/", "");
				String fileSize = link.select("span:eq(1)").text();
				MagentInfo magentInfo = new MagentInfo(fileName, fileSize, magent);
				magentInfolist.add(magentInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("解析发生错误！！！");
		} finally {

		}
		return magentInfolist;
	}

	public static void main(String[] args) throws IOException {
		AbstractMagentSearch s = new TorrentbaMagentSearch();
		System.out.println(JSONUtil.toJsonStr(s.magentSearch("阿丽塔")));
	}

}
